<template>
  <div class="favorites-list">
    <div class="favorites-container">
      <!-- 搜索和筛选区域 -->
      <div class="favorites-header">
        <div class="search-section">
          <n-input
            v-model:value="searchKeyword"
            placeholder="搜索收藏的物品..."
            clearable
            @update:value="handleSearch"
            style="width: 300px"
          >
            <template #prefix>
              <n-icon>
                <SearchOutline />
              </n-icon>
            </template>
          </n-input>
        </div>

        <div class="filter-section">
          <n-select
            v-model:value="selectedType"
            :options="typeOptions"
            placeholder="选择类型"
            style="width: 120px"
            @update:value="handleTypeChange"
          />
          <n-select
            v-model:value="selectedGrade"
            :options="gradeOptions"
            placeholder="选择等级"
            style="width: 120px"
            @update:value="handleGradeChange"
          />
          <n-select
            v-model:value="sortBy"
            :options="sortOptions"
            placeholder="排序方式"
            style="width: 140px"
            @update:value="handleSortChange"
          />
        </div>

        <div class="action-section">
          <n-button
            v-if="selectedItems.length > 0"
            type="error"
            @click="handleBatchRemove"
            :loading="batchRemoving"
          >
            批量删除 ({{ selectedItems.length }})
          </n-button>
        </div>
      </div>

      <!-- 收藏统计 -->
      <div v-if="!loading && favoritesList.length > 0" class="favorites-stats">
        <div class="stats-item">
          <span class="stats-label">总收藏:</span>
          <span class="stats-value">{{ total }}</span>
        </div>
        <div class="stats-item">
          <span class="stats-label">总价值:</span>
          <span class="stats-value">{{ formatPrice(totalValue) }} 哈夫币</span>
        </div>
      </div>

      <div class="favorites-content">
        <div v-if="loading" class="loading-container">
          <n-spin size="large" />
        </div>

        <div v-else-if="favoritesList.length > 0" class="favorites-grid">
          <div
            v-for="item in favoritesList"
            :key="item.id"
            class="favorite-card"
            :class="{
              selected: selectedItems.includes(item.id),
              [`grade-${item.object?.grade || 0}`]: true
            }"
            @click="handleItemClick(item)"
          >
            <div class="card-header">
              <n-checkbox
                :checked="selectedItems.includes(item.id)"
                @update:checked="(checked: boolean) => handleItemSelect(item.id, checked)"
                @click.stop
              />
              <div class="grade-badge" :class="`grade-${item.object?.grade || 0}`">
                {{ getGradeName(item.object?.grade || 0) }}
              </div>
              <n-button
                text
                type="error"
                size="small"
                @click.stop="handleRemoveSingle(item)"
                :loading="removingItems.includes(item.id)"
              >
                <template #icon>
                  <n-icon>
                    <TrashOutline />
                  </n-icon>
                </template>
              </n-button>
            </div>

            <div class="card-content">
              <div class="item-image" :class="`grade-bg-${item.object?.grade || 0}`">
                <img
                  v-if="item.object?.pic"
                  :src="item.object.pic"
                  :alt="item.object?.object_name"
                  @error="handleImageError"
                  loading="lazy"
                />
              </div>

              <div class="item-info">
                <h3 class="item-name">{{ item.object?.object_name || '未知物品' }}</h3>
                <p class="item-description">{{ item.object?.desc || '暂无描述' }}</p>

                <div class="item-details">
                  <div class="detail-row">
                    <span class="detail-label">价格:</span>
                    <span class="detail-value price">{{ formatPrice(item.object?.avg_price || 0) }} 哈夫币</span>
                  </div>
                  <div class="detail-row" v-if="item.object?.weight">
                    <span class="detail-label">重量:</span>
                    <span class="detail-value">{{ item.object.weight }}kg</span>
                  </div>
                  <div class="detail-row" v-if="item.object?.length && item.object?.width">
                    <span class="detail-label">尺寸:</span>
                    <span class="detail-value">{{ item.object.length }}×{{ item.object.width }}</span>
                  </div>
                </div>

                <div class="item-meta">
                  <span class="item-type">{{ formatType(item.object_type) }}</span>
                  <span class="favorite-time">{{ formatTime(item.create_time) }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>

        <n-empty v-else description="暂无收藏" size="large">
          <template #extra>
            <n-button @click="$router.push('/items')">
              去逛逛
            </n-button>
          </template>
        </n-empty>

        <!-- 分页 -->
        <div v-if="totalPages > 1" class="pagination-container">
          <n-pagination
            v-model:page="currentPage"
            :page-count="totalPages"
            :page-size="pageSize"
            show-size-picker
            :page-sizes="[10, 20, 50]"
            @update:page="handlePageChange"
            @update:page-size="handlePageSizeChange"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { useMessage, useDialog } from 'naive-ui'
import { getFavorites, removeFavorite } from '@/api/account'
import { formatTimestamp } from '@/utils/auth'
import { formatHafCoin, formatDate } from '@/utils/format'
import type { FavoriteItem, FavoritesQueryParams } from '@/types/user'
import {
  TrashOutline,
  ImageOutline,
  SearchOutline
} from '@vicons/ionicons5'

const router = useRouter()
const message = useMessage()
const dialog = useDialog()

// 状态
const loading = ref(false)
const batchRemoving = ref(false)
const removingItems = ref<number[]>([])
const selectedItems = ref<number[]>([])

// 搜索和筛选
const searchKeyword = ref('')
const selectedType = ref('all')
const selectedGrade = ref('all')
const sortBy = ref('create_time_desc')

// 数据
const favoritesList = ref<FavoriteItem[]>([])
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)

// 缓存
const dataCache = ref<Map<string, { data: any, timestamp: number }>>(new Map())
const CACHE_DURATION = 5 * 60 * 1000 // 5分钟缓存

// 选项配置
const typeOptions = [
  { label: '全部', value: 'all' },
  { label: '物品', value: 'item' },
  { label: '其他', value: 'other' }
]

const gradeOptions = [
  { label: '全部等级', value: 'all' },
  { label: '白色', value: 0 },
  { label: '灰色', value: 1 },
  { label: '绿色', value: 2 },
  { label: '蓝色', value: 3 },
  { label: '紫色', value: 4 },
  { label: '橙色', value: 5 },
  { label: '红色', value: 6 }
]

const sortOptions = [
  { label: '收藏时间↓', value: 'create_time_desc' },
  { label: '收藏时间↑', value: 'create_time_asc' },
  { label: '物品名称↓', value: 'object_name_desc' },
  { label: '物品名称↑', value: 'object_name_asc' },
  { label: '价格↓', value: 'avg_price_desc' },
  { label: '价格↑', value: 'avg_price_asc' }
]

// 计算属性
const totalPages = computed(() => Math.ceil(total.value / pageSize.value))

const totalValue = computed(() => {
  return favoritesList.value.reduce((sum, item) => {
    return sum + (item.object?.avg_price || 0)
  }, 0)
})

// 工具方法
const formatType = (type: string): string => {
  const typeMap: Record<string, string> = {
    item: '物品',
    other: '其他'
  }
  return typeMap[type] || type
}

const formatTime = (timeStr: string): string => {
  return formatDate(timeStr, 'full')
}

const formatPrice = (price: number): string => {
  return formatHafCoin(price)
}

const getGradeName = (grade: number): string => {
  const gradeNames = ['白', '灰', '绿', '蓝', '紫', '橙', '红']
  return gradeNames[grade] || '未知'
}

// 获取收藏列表
const fetchFavorites = async (useCache = true) => {
  try {
    loading.value = true

    // 构建查询参数
    const params: FavoritesQueryParams = {
      page: currentPage.value,
      limit: pageSize.value,
      type: selectedType.value === 'all' ? undefined : selectedType.value,
      grade: selectedGrade.value === 'all' ? undefined : Number(selectedGrade.value),
      search: searchKeyword.value || undefined
    }

    // 处理排序参数
    const [sortField, sortOrder] = sortBy.value.split('_')
    if (sortField && sortOrder) {
      params.sort = sortField as any
      params.order = sortOrder as 'asc' | 'desc'
    }

    // 生成缓存键
    const cacheKey = JSON.stringify(params)

    // 检查缓存
    if (useCache && dataCache.value.has(cacheKey)) {
      const cached = dataCache.value.get(cacheKey)!
      if (Date.now() - cached.timestamp < CACHE_DURATION) {
        favoritesList.value = cached.data.list
        total.value = cached.data.total
        loading.value = false
        return
      }
    }

    const response = await getFavorites(params)
    if (response.code === 1) {
      favoritesList.value = response.data.list
      total.value = response.data.total

      // 缓存数据
      dataCache.value.set(cacheKey, {
        data: response.data,
        timestamp: Date.now()
      })
    }
  } catch (error) {
    console.error('获取收藏列表失败:', error)
    message.error('获取收藏列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索处理（防抖）
let searchTimer: NodeJS.Timeout | null = null
const handleSearch = () => {
  if (searchTimer) {
    clearTimeout(searchTimer)
  }
  searchTimer = setTimeout(() => {
    currentPage.value = 1
    selectedItems.value = []
    fetchFavorites()
  }, 500)
}

// 筛选和排序处理
const handleTypeChange = () => {
  currentPage.value = 1
  selectedItems.value = []
  fetchFavorites()
}

const handleGradeChange = () => {
  currentPage.value = 1
  selectedItems.value = []
  fetchFavorites()
}

const handleSortChange = () => {
  currentPage.value = 1
  selectedItems.value = []
  fetchFavorites()
}

// 处理页码变化
const handlePageChange = (page: number) => {
  currentPage.value = page
  selectedItems.value = []
  fetchFavorites()
}

// 处理页面大小变化
const handlePageSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
  selectedItems.value = []
  fetchFavorites()
}

// 处理项目选择
const handleItemSelect = (id: number, checked: boolean) => {
  if (checked) {
    selectedItems.value.push(id)
  } else {
    const index = selectedItems.value.indexOf(id)
    if (index > -1) {
      selectedItems.value.splice(index, 1)
    }
  }
}

// 处理项目点击
const handleItemClick = (item: FavoriteItem) => {
  // 根据收藏类型跳转到对应页面
  if (item.object_type === 'item') {
    router.push(`/items/${item.object_id}`)
  }
}

// 处理单个删除
const handleRemoveSingle = async (item: FavoriteItem) => {
  dialog.warning({
    title: '确认删除',
    content: `确定要取消收藏"${item.object?.object_name || '该物品'}"吗？`,
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: async () => {
      try {
        removingItems.value.push(item.id)
        await removeFavorite({
          object_id: item.object_id,
          object_type: item.object_type
        })

        message.success('取消收藏成功')
        // 清除缓存并重新获取数据
        dataCache.value.clear()
        await fetchFavorites(false)
      } catch (error: any) {
        console.error('取消收藏失败:', error)
        message.error(error.message || '取消收藏失败')
      } finally {
        const index = removingItems.value.indexOf(item.id)
        if (index > -1) {
          removingItems.value.splice(index, 1)
        }
      }
    }
  })
}

// 处理批量删除
const handleBatchRemove = () => {
  dialog.warning({
    title: '确认批量删除',
    content: `确定要取消收藏选中的 ${selectedItems.value.length} 个物品吗？`,
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: async () => {
      try {
        batchRemoving.value = true
        
        // 获取选中的收藏项
        const selectedFavorites = favoritesList.value.filter(item => 
          selectedItems.value.includes(item.id)
        )
        
        // 批量删除
        await Promise.all(
          selectedFavorites.map(item =>
            removeFavorite({
              object_id: item.object_id,
              object_type: item.object_type
            })
          )
        )
        
        message.success('批量取消收藏成功')
        selectedItems.value = []
        // 清除缓存并重新获取数据
        dataCache.value.clear()
        await fetchFavorites(false)
      } catch (error: any) {
        console.error('批量取消收藏失败:', error)
        message.error(error.message || '批量取消收藏失败')
      } finally {
        batchRemoving.value = false
      }
    }
  })
}

// 处理图片错误
const handleImageError = (event: Event) => {
  const img = event.target as HTMLImageElement
  img.style.display = 'none'
}

// 组件挂载
onMounted(() => {
  fetchFavorites()
})
</script>

<style scoped>
.favorites-list {
  padding: 0;
}

.favorites-header {
  display: flex;
  flex-direction: column;
  gap: 16px;
  margin-bottom: 24px;
  padding: 20px;
  background: var(--n-card-color);
  border-radius: 12px;
  border: 1px solid var(--n-border-color);
}

.search-section {
  display: flex;
  align-items: center;
}

.filter-section {
  display: flex;
  align-items: center;
  gap: 12px;
  flex-wrap: wrap;
}

.action-section {
  display: flex;
  justify-content: flex-end;
}

.favorites-stats {
  display: flex;
  gap: 24px;
  margin-bottom: 20px;
  padding: 16px 20px;
  background: var(--n-card-color);
  border-radius: 8px;
  border: 1px solid var(--n-border-color);
}

.stats-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.stats-label {
  color: var(--n-text-color-2);
  font-size: 14px;
}

.stats-value {
  font-weight: 600;
  color: var(--n-text-color-1);
}

.loading-container {
  display: flex;
  justify-content: center;
  padding: 60px;
}

.favorites-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
  margin-bottom: 32px;
}

.favorite-card {
  border: 1px solid var(--n-border-color);
  border-radius: 12px;
  padding: 16px;
  cursor: pointer;
  transition: all 0.2s ease;
  background: var(--n-card-color);
  position: relative;
  overflow: hidden;
}

.favorite-card:hover {
  border-color: var(--n-primary-color);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.favorite-card.selected {
  border-color: var(--n-primary-color);
  background: var(--n-primary-color-hover);
}

/* 等级边框颜色 - 使用全局颜色系统 */
.favorite-card.grade-0 { border-left: 4px solid var(--grade-0-color); }
.favorite-card.grade-1 { border-left: 4px solid var(--grade-1-color); }
.favorite-card.grade-2 { border-left: 4px solid var(--grade-2-color); }
.favorite-card.grade-3 { border-left: 4px solid var(--grade-3-color); }
.favorite-card.grade-4 { border-left: 4px solid var(--grade-4-color); }
.favorite-card.grade-5 { border-left: 4px solid var(--grade-5-color); }
.favorite-card.grade-6 { border-left: 4px solid var(--grade-6-color); }

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.grade-badge {
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 600;
  color: white;
}

.grade-badge.grade-0 { background: var(--grade-0-color); }
.grade-badge.grade-1 { background: var(--grade-1-color); }
.grade-badge.grade-2 { background: var(--grade-2-color); }
.grade-badge.grade-3 { background: var(--grade-3-color); }
.grade-badge.grade-4 { background: var(--grade-4-color); }
.grade-badge.grade-5 { background: var(--grade-5-color); }
.grade-badge.grade-6 { background: var(--grade-6-color); }

.card-content {
  display: flex;
  gap: 12px;
}

.item-image {
  width: 80px;
  height: 80px;
  border-radius: 8px;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
  position: relative;
}

/* 等级背景颜色 - 使用全局颜色系统 */
.item-image.grade-bg-0 { background: var(--grade-0-bg); }
.item-image.grade-bg-1 { background: var(--grade-1-bg); }
.item-image.grade-bg-2 { background: var(--grade-2-bg); }
.item-image.grade-bg-3 { background: var(--grade-3-bg); }
.item-image.grade-bg-4 { background: var(--grade-4-bg); }
.item-image.grade-bg-5 { background: var(--grade-5-bg); }
.item-image.grade-bg-6 { background: var(--grade-6-bg); }

.item-image img {
  width: 100%;
  height: 100%;
  object-fit: contain;
  border-radius: 6px;
}


.item-info {
  flex: 1;
  min-width: 0;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.item-name {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  color: var(--n-text-color-1);
}

.item-description {
  margin: 0;
  font-size: 13px;
  color: var(--n-text-color-2);
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.item-details {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.detail-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
}

.detail-label {
  color: var(--n-text-color-3);
  min-width: 40px;
}

.detail-value {
  color: var(--n-text-color-2);
  font-weight: 500;
}

.detail-value.price {
  color: var(--n-primary-color);
  font-weight: 600;
}

.item-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
}

.item-type {
  color: var(--n-primary-color);
  background: var(--n-primary-color-hover);
  padding: 2px 8px;
  border-radius: 4px;
}

.favorite-time {
  color: var(--n-text-color-3);
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 32px;
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .favorites-header {
    padding: 16px;
  }

  .filter-section {
    gap: 8px;
  }

  .favorites-grid {
    grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
    gap: 16px;
  }
}

@media (max-width: 768px) {
  .favorites-list {
    padding: 12px;
  }

  .favorites-header {
    padding: 16px;
    gap: 12px;
  }

  .search-section {
    width: 100%;
  }

  .search-section .n-input {
    width: 100% !important;
  }

  .filter-section {
    width: 100%;
    justify-content: space-between;
  }

  .filter-section .n-select {
    flex: 1;
    min-width: 80px !important;
    width: auto !important;
  }

  .action-section {
    width: 100%;
  }

  .favorites-stats {
    flex-direction: column;
    gap: 12px;
    padding: 12px 16px;
  }

  .favorites-grid {
    grid-template-columns: 1fr;
    gap: 12px;
  }

  .favorite-card {
    padding: 12px;
  }

  .card-content {
    gap: 12px;
  }

  .item-image {
    width: 60px;
    height: 60px;
  }

  .item-details {
    gap: 2px;
  }

  .detail-row {
    font-size: 11px;
  }
}

@media (max-width: 480px) {
  .favorites-header {
    padding: 12px;
  }

  .filter-section {
    flex-direction: column;
    gap: 8px;
  }

  .filter-section .n-select {
    width: 100% !important;
  }

  .card-content {
    flex-direction: column;
    text-align: center;
  }

  .item-image {
    align-self: center;
    width: 80px;
    height: 80px;
  }

  .item-info {
    align-items: center;
  }

  .item-meta {
    flex-direction: column;
    gap: 4px;
    align-items: center;
  }
}
</style>
